package cn.itcast.n4.exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
    public static void main(String[] args) throws InterruptedException {
        final int ticketNum = 1000;
        final int personNum = 2000;
        // 模拟多人买票,余票1000张
        TicketWindow window = new TicketWindow(ticketNum);

        //记录卖出的票数
        AtomicInteger sellNum = new AtomicInteger();

        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < personNum; i++) {
            Thread thread = new Thread(() -> {
                int amount = window.sell(random(5));

                try {
                    Thread.sleep(random(10));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sellNum.getAndAdd(amount);

            });
            threadList.add(thread);
            thread.start();
        }

        for (Thread thread : threadList) {
            thread.join(); // 主线程等待线程执行结束
        }

        log.debug("剩余票数；{}", window.getCount());
        log.debug("卖出票数：{}", sellNum.get());

    }

    // Random 为线程安全
    static Random random = new Random();

    // 随机 1~5
    public static int random(int amount) {
        return random.nextInt(amount) + 1;
    }
}

// 售票窗口
class TicketWindow {
    //剩余数量
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    // 获取余票数量
    public int getCount() {
        return count;
    }

    // 售票
    public synchronized int sell(int amount) {
        //临界区，多个线程对多个资源进行操作
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}